# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html

import pymysql
'''
create database spider;
CREATE TABLE IF NOT EXISTS `zhaobiao` (
    `web` VARCHAR(255) ,
    `projectcode` VARCHAR(255),
    `keyword` VARCHAR(255),
    `detail_url` VARCHAR(511) not null unique,
    `title` VARCHAR(1023),
    `toptype` VARCHAR(255),
    `province` VARCHAR(255),
    `product` VARCHAR(255),
    `industry` VARCHAR(255),
    `tendering_manner` VARCHAR(255),
    `publicity_date` VARCHAR(255),
    `expiry_date` VARCHAR(255)
) CHARSET=utf8;
'''


class ZhaobiaoPipeline(object):
    def __init__(self):
        self.db = pymysql.connect("localhost", "root", "apple123", "spider")
        self.cursor = self.db.cursor()

    def process_item(self, item, spider):
        sql_key = ",".join(item.keys())
        sql_val = ",".join(['"%s"' % item[k] for k in item.keys()])
        sql = "insert into zhaobiao (%s) value (%s);" % (sql_key, sql_val)
        try:
            self.cursor.execute(sql)
            self.db.commit()
        except pymysql.err.IntegrityError as e:
            # just ignore the integrity error for duplicated scapied
            pass
